package com.sunwayworld.basemodule.rm.equipment.equipscrap.service.impl;

import com.sunwayworld.basemodule.rm.equipment.bean.LimsEquipmentBean;
import com.sunwayworld.basemodule.rm.equipment.equipscrap.bean.LimsEquipScrapBean;
import com.sunwayworld.basemodule.rm.equipment.equipscrap.dao.LimsEquipScrapDao;
import com.sunwayworld.basemodule.rm.equipment.equipscrap.service.LimsEquipScrapService;
import com.sunwayworld.basemodule.rm.equipment.service.LimsEquipmentService;
import com.sunwayworld.framework.at.annotation.AuditTrailEntry;
import com.sunwayworld.framework.at.annotation.AuditTrailType;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Repository
@GikamBean
public class LimsEquipScrapServiceImpl implements LimsEquipScrapService {

    @Autowired
    private LimsEquipScrapDao limsEquipScrapDao;

    @Autowired
    @Lazy
    private LimsEquipmentService limsEquipmentService;

    @Override
    @SuppressWarnings("unchecked")
    public LimsEquipScrapDao getDao() {
        return limsEquipScrapDao;
    }

    @Override
    @Transactional
    @AuditTrailEntry(AuditTrailType.INSERT)
    public Long insert(RestJsonWrapperBean jsonWrapper) {
        LimsEquipScrapBean limsEquipScrap = jsonWrapper.parseUnique(LimsEquipScrapBean.class);
        limsEquipScrap.setId(ApplicationContextHelper.getNextIdentity());
        getDao().insert(limsEquipScrap);
        return limsEquipScrap.getId();
    }

    @Override
    @Transactional
    public void afterScrapDone(List<Long> ids) {
        List<LimsEquipScrapBean> beans = this.selectListByIds(ids);
        if (beans.isEmpty()) {
            return;
        }
        List<Long> equipIds = beans.stream().map(LimsEquipScrapBean::getEquipmentId).filter(Objects::nonNull).collect(Collectors.toList());
        LimsEquipmentBean update = new LimsEquipmentBean();
        update.setEquipState("scrapped");
        limsEquipmentService.getDao().updateByIds(update, equipIds, "equipState");
    }
}
